package com.delivery.deliverysystem.common;

import com.delivery.deliverysystem.pojo.DAO.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
public class DataSourceBean {
    /**
     * 加载送货单的数据源
     *
     * @param dsName
     * @param dataSetName
     * @param parameters
     * @return
     */
    public List<Map<String, Object>> loadPdfData(String dsName, String dataSetName, Map<String, Object> parameters) {
        try {
            String data = parameters.get("data").toString();
            // 清理非法字符（如空格、换行等）
            data = data.replaceAll("\\s", "");

            // 使用 URL 安全的 Base64 解码器
            byte[] decodedBytes = Base64.getUrlDecoder().decode(data);
            String jsonData = new String(decodedBytes, StandardCharsets.UTF_8);

            // 解析 JSON
            PdfDAO pdfDAO = new ObjectMapper().readValue(jsonData, PdfDAO.class);

            List<Map<String, Object>> list = new ArrayList<>();

            // 公司信息
            Map<String, Object> companyInfo = new HashMap<>();
            companyInfo.put("fullName", pdfDAO.getFullName());
            companyInfo.put("address", pdfDAO.getAddress());
            companyInfo.put("companyPhone", pdfDAO.getCompanyPhone());
            companyInfo.put("companyFax", pdfDAO.getCompanyFax());
            companyInfo.put("companyLogo", pdfDAO.getCompanyLogo());
            list.add(companyInfo);

            // 客户信息
            Map<String, Object> clientInfo = new HashMap<>();
            clientInfo.put("clientName", pdfDAO.getClientName());
            clientInfo.put("clientAddress", pdfDAO.getClientAddress());
            clientInfo.put("deliveryId", pdfDAO.getDeliveryId());
            clientInfo.put("department", pdfDAO.getDepartment());
            clientInfo.put("clientPhone", pdfDAO.getClientPhone());
            clientInfo.put("username", pdfDAO.getUsername());
            clientInfo.put("deliveryDate", pdfDAO.getDeliveryDate());
            clientInfo.put("contact", pdfDAO.getContact());
            list.add(clientInfo);

            // 产品信息
            for (ProductPdfDAO product : pdfDAO.getProductPdfDAO()) {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("ordinal", product.getOrdinal());
                productMap.put("productId", product.getProductId());
                productMap.put("productName", product.getProductName());
                productMap.put("number", product.getNumber());
                productMap.put("unit", product.getUnit());
                productMap.put("total", product.getTotal());
                productMap.put("price", product.getPrice());
                productMap.put("money", product.getMoney());
                productMap.put("remark", product.getRemark());
                list.add(productMap);
            }

            return list;
        } catch (Exception e) {
            throw new RuntimeException("解析PDF数据失败", e);
        }
    }

    /**
     * 加载对账单的数据源
     *
     * @param dsName
     * @param dataSetName
     * @param parameters
     * @return
     */
    public List<Map<String, Object>> loadPdfData1(String dsName, String dataSetName, Map<String, Object> parameters) {
        try {
            String data = parameters.get("data").toString();
            // 清理非法字符（如空格、换行等）
            data = data.replaceAll("\\s", "");

            // 使用 URL 安全的 Base64 解码器
            byte[] decodedBytes = Base64.getUrlDecoder().decode(data);
            String jsonData = new String(decodedBytes, StandardCharsets.UTF_8);

            // 解析 JSON
            ReconciliationDAO reconciliationDAO = new ObjectMapper().readValue(jsonData, ReconciliationDAO.class);


            // 3. 构建数据列表（原有逻辑不变）
            List<Map<String, Object>> list = new ArrayList<>();

            // 公司信息
            Map<String, Object> companyInfo = new HashMap<>();
            companyInfo.put("fullName", reconciliationDAO.getFullName());
            companyInfo.put("address", reconciliationDAO.getAddress());
            companyInfo.put("companyPhone", reconciliationDAO.getCompanyPhone());
            companyInfo.put("companyFax", reconciliationDAO.getCompanyFax());
            list.add(companyInfo);

            // 客户信息
            Map<String, Object> clientInfo = new HashMap<>();
            clientInfo.put("clientName", reconciliationDAO.getClientName());
            clientInfo.put("contact", reconciliationDAO.getContact());
            list.add(clientInfo);

            // 产品信息（修正了字段映射错误）
            for (ReconcileProductsDAO reconcile : reconciliationDAO.getReconcileProductsDAOS()) {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("ordinal", reconcile.getOrdinal());
                productMap.put("deliveryId", reconcile.getDeliveryId());
                productMap.put("deliveryDate", reconcile.getDeliveryDate()); // 修正：原代码错误使用了deliveryId
                productMap.put("productName", reconcile.getProductName());   // 修正：原代码错误使用了deliveryDate
                productMap.put("unit", reconcile.getUnit());
                productMap.put("total", reconcile.getTotal());
                productMap.put("price", reconcile.getPrice());
                productMap.put("remark", reconcile.getRemark());
                list.add(productMap);
            }

            // 对账时间信息
            Map<String, Object> reconciliationTime = new HashMap<>();
            reconciliationTime.put("beginTime", reconciliationDAO.getBeginTime());
            reconciliationTime.put("endTime", reconciliationDAO.getEndTime());
            list.add(reconciliationTime);

            return list;

        } catch (Exception e) {
            throw new RuntimeException("解析对账单数据失败", e);
        }
    }

    /**
     * 加载标签表的数据源
     *
     * @param dsName
     * @param dataSetName
     * @param parameters
     * @return
     */
    public List<Map<String, Object>> loadPdfData2(String dsName, String dataSetName, Map<String, Object> parameters) {
        try {
            String data = parameters.get("data").toString();
            // 清理非法字符（如空格、换行等）
            data = data.replaceAll("\\s", "");

            // 使用 URL 安全的 Base64 解码器
            byte[] decodedBytes = Base64.getUrlDecoder().decode(data);
            String jsonData = new String(decodedBytes, StandardCharsets.UTF_8);

            // 2. 反序列化对象
            LabelDAO labelDAO = new ObjectMapper().readValue(jsonData, LabelDAO.class);

            // 3. 构建数据列表
            List<Map<String, Object>> list = new ArrayList<>();

            Map<String, Object> labelMap = new HashMap<>();
            labelMap.put("fullName", labelDAO.getFullName());
            labelMap.put("clientName", labelDAO.getClientName());
            labelMap.put("modelNumber", labelDAO.getModelNumber());
            labelMap.put("bladeMouldNumber", labelDAO.getBladeMouldNumber());
            labelMap.put("modelType", labelDAO.getModelType());
            labelMap.put("date", labelDAO.getDate());
            labelMap.put("remark", labelDAO.getRemark());
            list.add(labelMap);

            return list;

        } catch (Exception e) {
            throw new RuntimeException("解析标签数据失败", e);
        }
    }

    /**
     * 加载检测报告表的数据源
     *
     * @param dsName
     * @param dataSetName
     * @param parameters
     * @return
     */
    public List<Map<String, Object>> loadPdfData3(String dsName, String dataSetName, Map<String, Object> parameters) throws JsonProcessingException {

        try {
            String data = parameters.get("data").toString();
            // 清理非法字符（如空格、换行等）
            data = data.replaceAll("\\s", "");

            // 使用 URL 安全的 Base64 解码器
            byte[] decodedBytes = Base64.getUrlDecoder().decode(data);
            String jsonData = new String(decodedBytes, StandardCharsets.UTF_8);
            // 2. 反序列化检测报告对象
            DetectReportDAO detectReportDAO = new ObjectMapper()
                    .readValue(jsonData, DetectReportDAO.class);

            // 3. 构建数据列表
            List<Map<String, Object>> list = new ArrayList<>();

            // 公司信息
            Map<String, Object> companyInfo = new HashMap<>();
            companyInfo.put("fullName", detectReportDAO.getFullName());
            companyInfo.put("companyPhone", detectReportDAO.getCompanyPhone());
            companyInfo.put("companyFax", detectReportDAO.getCompanyFax());
            list.add(companyInfo);

            // 客户信息
            Map<String, Object> clientInfo = new HashMap<>();
            clientInfo.put("clientName", detectReportDAO.getClientName());
            clientInfo.put("documentNumber", detectReportDAO.getDocumentNumber());
            clientInfo.put("deliveryDate", detectReportDAO.getDeliveryDate());
            clientInfo.put("provider", detectReportDAO.getProvider());
            clientInfo.put("bladeMouldNumber", detectReportDAO.getBladeMouldNumber());
            clientInfo.put("tolerance", detectReportDAO.getTolerance());
            clientInfo.put("testEquipment", detectReportDAO.getTestEquipment());
            clientInfo.put("bladeHight", detectReportDAO.getBladeHight());
            clientInfo.put("question", detectReportDAO.getQuestion());
            clientInfo.put("result", detectReportDAO.getResult());
            clientInfo.put("reviewer", detectReportDAO.getReviewer());
            clientInfo.put("detectTime", detectReportDAO.getDetectTime());
            list.add(clientInfo);

            // 检测详细信息
            for (InspectionDetailDAO detail : detectReportDAO.getInspectionDetailDAOS()) {
                Map<String, Object> detailMap = new HashMap<>();
                detailMap.put("ordinal", detail.getOrdinal());
                detailMap.put("standardSize", detail.getStandardSize());
                detailMap.put("actualSize", detail.getActualSize());
                detailMap.put("first", detail.getFirst());
                detailMap.put("second", detail.getSecond());
                detailMap.put("third", detail.getThird());
                detailMap.put("fourth", detail.getFourth());
                detailMap.put("fifth", detail.getFifth());
                detailMap.put("sixth", detail.getSixth());
                detailMap.put("seventh", detail.getSeventh());
                detailMap.put("eighth", detail.getEighth());
                list.add(detailMap);
            }

            return list;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
        /**
     * 加载报价单表的数据源
     *
     * @param dsName
     * @param dataSetName
     * @param parameters
     * @return
     */
    public List<Map<String, Object>> loadPdfData4(String dsName, String dataSetName, Map<String, Object> parameters) {
        try {
            String data = parameters.get("data").toString();
            // 清理非法字符（如空格、换行等）
            data = data.replaceAll("\\s", "");

            // 使用 URL 安全的 Base64 解码器
            byte[] decodedBytes = Base64.getUrlDecoder().decode(data);
            String jsonData = new String(decodedBytes, StandardCharsets.UTF_8);
            QuotationDAO quotationDAO = new ObjectMapper().readValue(jsonData, QuotationDAO.class);

            List<Map<String, Object>> list = new ArrayList<>();

            // 公司信息
            Map<String, Object> companyInfo = new HashMap<>();
            companyInfo.put("fullName", quotationDAO.getFullName());
            companyInfo.put("address", quotationDAO.getAddress());
            companyInfo.put("companyPhone", quotationDAO.getCompanyPhone());
            companyInfo.put("companyFax", quotationDAO.getCompanyFax());
            list.add(companyInfo);

            // 客户信息
            Map<String, Object> clientInfo = new HashMap<>();
            clientInfo.put("clientNumber", quotationDAO.getClientNumber());
            clientInfo.put("clientName", quotationDAO.getClientName());
            clientInfo.put("contact", quotationDAO.getContact());
            clientInfo.put("clientTEL", quotationDAO.getClientTEL());
            clientInfo.put("clientPhone", quotationDAO.getClientPhone());
            clientInfo.put("quoteTime", quotationDAO.getQuoteTime());
            clientInfo.put("offeror", quotationDAO.getOfferor());
            clientInfo.put("offerorPhone", quotationDAO.getOfferorPhone());
            clientInfo.put("payMethod", quotationDAO.getPayMethod());
            clientInfo.put("deliveryDeadlines", quotationDAO.getDeliveryDeadlines());
            clientInfo.put("productName", quotationDAO.getProductName());
            clientInfo.put("handler", quotationDAO.getHandler());
            clientInfo.put("handlerMobilePhone", quotationDAO.getHandlerMobilePhone());
            clientInfo.put("handlerStraightLine", quotationDAO.getHandlerStraightLine());
            clientInfo.put("remark", quotationDAO.getRemark());
            clientInfo.put("image", quotationDAO.getImage());
            clientInfo.put("money", quotationDAO.getMoney());
            list.add(clientInfo);

            // 报价单项目详情
            for (QuoteItemDAO item : quotationDAO.getQuoteItemDAOS()) {
                Map<String, Object> itemMap = new HashMap<>();
                itemMap.put("quoteId", item.getQuoteId());
                itemMap.put("quoteName", item.getQuoteName());
                itemMap.put("unit", item.getUnit());
                itemMap.put("price", item.getPrice());
                itemMap.put("total", item.getTotal());
                list.add(itemMap);
            }

            return list;
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
